<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>矩形碰撞检测</title>
</head>
<body style="margin: 0;padding: 0;" onload="draw()">
<canvas id="canvas" width="800px" height="400px" style="border: solid 1px #000;"></canvas>
<script>
function draw(){
  let canvas = document.querySelector("#canvas");
  if(canvas.getContext){
    //创建context对象
    let cvsCtx = canvas.getContext("2d");
    //1.绘制图像
    //2.清除画布
    //3.更新位置
    //4.绘制图像 2. 3. 4.
    //面向对象
    function Rect(x,y,width,height,color,speedX){
      this.x = x;
      this.y = y;
      this.width = width;
      this.height = height;
      this.color = color;
      this.speedX = speedX;
    }
    Rect.prototype.draw = function(){
      cvsCtx.beginPath();
      cvsCtx.fillStyle = this.color;
      cvsCtx.fillRect(this.x, this.y, this.width, this.height);
      cvsCtx.closePath();
    } 
    Rect.prototype.move = function(){
      
      //更新位置
      this.x += this.speedX;
      if(this.x > canvas.width-this.width || this.x < 0){
        this.speedX *= -1;
      }

    }
    function init(){
      //清除画布
      cvsCtx.clearRect(0, 0, canvas.width, canvas.height);
      rect1.draw();
      rect1.move();
      rect2.draw();
      rect2.move();
      //检测
      if(isRectHit(rect1,rect2)){
        rect1.speedX *= -1;
        rect2.speedX *= -1;
      }
      //请求关键帧动画
      window.requestAnimationFrame(init);
    } 
    function isRectHit(rect1,rect2){
      let min1 = rect1.x;
      let min2 = rect2.x;
      let max1 = rect1.x + rect1.width;
      let max2 = rect2.x + rect2.width;
      
      let min3 = Math.max(min1,min2);
      let max3 = Math.min(max1,max2);
      if(min3<=max3){
        return true;
      }
      return false;
    } 
    let rect1 = new Rect(0,200,150,150,'pink',4);
    let rect2 = new Rect(640,200,150,150,'skyblue',4);
    init();
    isRectHit(rect1,rect2);
  }
}
</script>
</body>
</html>